import { getTemplate, getAppid, SaveSelect } from '@/common/api'
import { appid } from '@/common/utils/config'

const model = {
	state: {
		indexModel: [],
		usersModel: {},
		navigator: {},
		shop: 0
	},
	mutations: {
		SET_INDEXMODEL: (state, indexModel) => { // 首页模板
			state.indexModel = indexModel
		},
		SET_USERCENTER: (state, usersModel) => { // 个人中心
			state.usersModel = usersModel
		},
		SET_SHOP: (state, shop) => { // 店铺信息
			state.shop = shop
		},
		SET_NAVIGATOR: (state, navigator) => { // 获取导航设置
			state.navigator = navigator
		},
		SET_SHOP_DESC: (state, desc) => { // 描述
			state.shop.desc = desc
		}
	},
	actions: {
		getModel ({ commit, dispatch, state }, use_appid) { // 获取模板信息
			return new Promise((resolve, reject) => {
				getTemplate({ use_appid }).then(res => {
					if (res.length) {
						let indexModel = []
						let navigator = {}
						let uModel = {}
						for (let i in res) {
							if (!+res[i].differ) indexModel = JSON.parse(res[i].content)
							if (+res[i].differ === 2) navigator = JSON.parse(res[i].content)[0]
							if (+res[i].differ === 3) uModel = JSON.parse(res[i].content)[0]
						}
						commit('SET_INDEXMODEL', indexModel) // 首页模板
						commit('SET_NAVIGATOR', navigator) // 导航设置
						uModel.limit_list = uModel.limit_list.filter(item => item.checked)
						commit('SET_USERCENTER', uModel) // 用户中心模板					
					} else {
						uni.showModal({
							showCancel: false,
							content: '没有获取到模板信息'
						})
					}
					resolve()
				}).catch(err => {
					console.log(err)
					reject(err)
				})				
			})
		},
		async GetAppid ({ commit, state }, appid) {
			const customer_id = await new Promise(resolve => {
				getAppid({ appid }).then(res => {
					if (!res.code) {
						res.data.customer_id = +res.data.customer_id
						commit('SET_SHOP', res.data)
						if (res.data.appkg) {
							uni.reLaunch({
								url: '/pages/defend/index'
							})
						}
						resolve(res.data.customer_id)
					} else {
						uni.showModal({
							title: '',
							content: '获取商户ID失败',
							showCancel: false
						})
					}
				})
			})
			await SaveSelect({ appid, customer_id }).then(res => {
				state.shop.type = res.message
				state.shop.appid = appid
				uni.setStorageSync('shop', state.shop)
			})
		}
	}
}

export default model